﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using Microsoft.DirectX.DirectSound;
using System.Diagnostics;
using System.Data.SqlClient;
using CoreAudioApi;

namespace SoundServant.Controls
{
    /// <summary>
    /// Interaction logic for ConfigControl.xaml
    /// </summary>
    public partial class ConfigControl : UserControl
    {
        private delegate void VoidInvokeHandler();
        Recorder jane;
        Burner max;
        Congregation congregation;
        Sharing sharing;
        MainWindow mainWindow;
        MMDevice recDevice;

        public void Tidy()
        {
            VolumeMeter.Stop();
        }

        public ConfigControl(Recorder _jane, Burner _max, Congregation _congregation, Sharing _sharing, MainWindow _window)
        {
            jane = _jane;
            max = _max;
            congregation = _congregation;
            sharing = _sharing;
            mainWindow = _window;
            InitializeComponent();

            VolumeMeter.Start();
            PopulateSongBooks();
            PopulateMeetingDays();
            SetupRecordingLevelSlider();

            // Set Options

            EnableSkypeCheckBox.IsChecked = congregation.SkypeEnabled;
            FullscreenModeCheckBox.IsChecked = SS.FullScreenMode;
            RevealNonRemovableStorageCheckBox.IsChecked = Options.Default.RevealFixedStorage;
            TouchScreenModeCheckBox.IsChecked = Options.Default.TouchScreenMode;
            WelcomeMusicVolumeSlider.Value = Options.Default.MusicVolume;
            WelcomeMusicVolumeTextBox.Text = Options.Default.MusicVolume.ToString();
            SnapshotSkypeCheckBox.IsChecked = Options.Default.SnapshotSkype;

            // Subscribe to Options Changed Events

            FullscreenModeCheckBox.Checked += new RoutedEventHandler(FullscreenModeCheckBox_Checked);
            FullscreenModeCheckBox.Unchecked += new RoutedEventHandler(FullscreenModeCheckBox_Unchecked);
            EnableSkypeCheckBox.Checked += new RoutedEventHandler(EnableSkypeCheckBox_Checked);
            EnableSkypeCheckBox.Unchecked += new RoutedEventHandler(EnableSkypeCheckBox_Unchecked);
            TouchScreenModeCheckBox.Checked += new RoutedEventHandler(TouchScreenModeCheckBox_Checked);
            TouchScreenModeCheckBox.Unchecked += new RoutedEventHandler(TouchScreenModeCheckBox_Unchecked);
            WelcomeMusicVolumeSlider.ValueChanged += new RoutedPropertyChangedEventHandler<double>(WelcomeMusicVolumeSlider_ValueChanged);
            CaptureDeviceComboBox.SelectionChanged += new SelectionChangedEventHandler(CaptureDeviceComboBox_SelectionChanged);
            RevealNonRemovableStorageCheckBox.Checked += new RoutedEventHandler(RevealNonRemovableStorageCheckBox_Checked);
            RevealNonRemovableStorageCheckBox.Unchecked += new RoutedEventHandler(RevealNonRemovableStorageCheckBox_Unchecked);
            RecordingLevelTrackBar.ValueChanged += new RoutedPropertyChangedEventHandler<double>(RecordingLevelTrackBar_ValueChanged);
            SnapshotSkypeCheckBox.Checked += new RoutedEventHandler(SnapshotSkypeCheckBox_Checked);
            SnapshotSkypeCheckBox.Unchecked += new RoutedEventHandler(SnapshotSkypeCheckBox_Unchecked);
        }

        void SnapshotSkypeCheckBox_Unchecked(object sender, RoutedEventArgs e)
        {
            Options.Default.SnapshotSkype = false;
        }

        void SnapshotSkypeCheckBox_Checked(object sender, RoutedEventArgs e)
        {
            Options.Default.SnapshotSkype = true;
        }

        void SetupRecordingLevelSlider()
        {
            MMDeviceEnumerator devEnum = new MMDeviceEnumerator();
            recDevice = devEnum.GetDefaultAudioEndpoint(EDataFlow.eCapture, ERole.eMultimedia);
            MMDeviceCollection deviceCollection = devEnum.EnumerateAudioEndPoints(EDataFlow.eCapture, EDeviceState.DEVICE_STATE_ACTIVE);
            for (int i = 0; i < deviceCollection.Count; i++)
            {
                AudioEndPointComboBoxItem audioEndPointComboBoxItem = new AudioEndPointComboBoxItem(deviceCollection[i]);
                if (audioEndPointComboBoxItem.EndPoint.ID == recDevice.ID) audioEndPointComboBoxItem.IsSelected = true;
                CaptureDeviceComboBox.Items.Add(audioEndPointComboBoxItem);
            }
            RecordingLevelLabel.Content = recDevice.AudioEndpointVolume.MasterVolumeLevel;
            RecordingLevelTrackBar.Minimum = recDevice.AudioEndpointVolume.VolumeRange.MindB;
            RecordingLevelTrackBar.Maximum = recDevice.AudioEndpointVolume.VolumeRange.MaxdB;
            RecordingLevelTrackBar.LargeChange = recDevice.AudioEndpointVolume.VolumeRange.IncrementdB;
            RecordingLevelTrackBar.Value = recDevice.AudioEndpointVolume.MasterVolumeLevel;

        }

        void PopulateMeetingDays()
        {
            switch (congregation.BstmssmDay)
            {
                case DayOfWeek.Monday:
                    BSTMSSMMondayRadioButton.IsChecked = true;
                    break;
                case DayOfWeek.Tuesday:
                    BSTMSSMTuesdayRadioButton.IsChecked = true;
                    break;
                case DayOfWeek.Wednesday:
                    BSTMSSMWednesdayRadioButton.IsChecked = true;
                    break;
                case DayOfWeek.Thursday:
                    BSTMSSMThursdayRadioButton.IsChecked = true;
                    break;
                case DayOfWeek.Friday:
                    BSTMSSMFridayRadioButton.IsChecked = true;
                    break;
                case DayOfWeek.Saturday:
                    BSTMSSMSaturdayRadioButton.IsChecked = true;
                    break;
                case DayOfWeek.Sunday:
                    BSTMSSMSundayRadioButton.IsChecked = true;
                    break;
                default:
                    break;
            }

            switch (congregation.PtwsDay)
            {
                case DayOfWeek.Monday:
                    PTWSMondayRadioButton.IsChecked = true;
                    break;
                case DayOfWeek.Tuesday:
                    PTWSTuesdayRadioButton.IsChecked = true;
                    break;
                case DayOfWeek.Wednesday:
                    PTWSWednesdayRadioButton.IsChecked = true;
                    break;
                case DayOfWeek.Thursday:
                    PTWSThursdayRadioButton.IsChecked = true;
                    break;
                case DayOfWeek.Friday:
                    PTWSFridayRadioButton.IsChecked = true;
                    break;
                case DayOfWeek.Saturday:
                    PTWSSaturdayRadioButton.IsChecked = true;
                    break;
                case DayOfWeek.Sunday:
                    PTWSSundayRadioButton.IsChecked = true;
                    break;
                default:
                    break;
            }
        }

        void RecordingLevelTrackBar_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            recDevice.AudioEndpointVolume.MasterVolumeLevel = (float)RecordingLevelTrackBar.Value;
            RecordingLevelLabel.Content = RecordingLevelTrackBar.Value.ToString("0");
        }

        void PopulateSongBooks()
        {
            SqlConnection connection = SS.Connection();
            SqlCommand command = new SqlCommand("SELECT * FROM songbooks", connection);
            SqlDataReader dataReader = command.ExecuteReader();

            if (dataReader.HasRows)
                while (dataReader.Read())
                {
                    SongBookRadioButton songBookRadioButton = new SongBookRadioButton((int)dataReader["songbookId"], (string)dataReader["songbookTitle"]);
                    if (songBookRadioButton.Id == congregation.Songbook) songBookRadioButton.IsChecked = true;
                    songBookRadioButton.Checked += new RoutedEventHandler(songBookRadioButton_Checked);
                    SongBooksStackPanel.Children.Add(songBookRadioButton);
                }

            dataReader.Close();
            connection.Close();
        }

        void songBookRadioButton_Checked(object sender, RoutedEventArgs e)
        {
            congregation.Songbook = ((SongBookRadioButton)sender).Id;
        }

        void RevealNonRemovableStorageCheckBox_Checked(object sender, RoutedEventArgs e)
        {
            Options.Default.RevealFixedStorage = true;
        }

        void RevealNonRemovableStorageCheckBox_Unchecked(object sender, RoutedEventArgs e)
        {
            Options.Default.RevealFixedStorage = false;
        }



        void FullscreenModeCheckBox_Unchecked(object sender, RoutedEventArgs e)
        {
            SS.FullScreenMode = false;
        }

        void FullscreenModeCheckBox_Checked(object sender, RoutedEventArgs e)
        {
            SS.FullScreenMode = true;
        }


        void ViewLogFilesButton_Click(object sender, RoutedEventArgs e)
        {
            mainWindow.WindowState = WindowState.Minimized;
        }

        void CaptureDeviceComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // ((AudioEndPointComboBoxItem)CaptureDeviceComboBox.SelectedItem).EndPoint.
        }

        void WelcomeMusicVolumeSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            WelcomeMusicVolumeTextBox.Text = WelcomeMusicVolumeSlider.Value.ToString("0");
            Options.Default.MusicVolume = (int)WelcomeMusicVolumeSlider.Value;
            jane.MusicVolume = (int)WelcomeMusicVolumeSlider.Value;
        }

        void TouchScreenModeCheckBox_Unchecked(object sender, RoutedEventArgs e)
        {
            Options.Default.TouchScreenMode = (bool)TouchScreenModeCheckBox.IsChecked;
        }

        void TouchScreenModeCheckBox_Checked(object sender, RoutedEventArgs e)
        {
            Options.Default.TouchScreenMode = (bool)TouchScreenModeCheckBox.IsChecked;
        }

        void EnableSkypeCheckBox_Unchecked(object sender, RoutedEventArgs e)
        {
            congregation.SkypeEnabled = (bool)EnableSkypeCheckBox.IsChecked;
        }

        void EnableSkypeCheckBox_Checked(object sender, RoutedEventArgs e)
        {
            congregation.SkypeEnabled = (bool)EnableSkypeCheckBox.IsChecked;
        }

        void PTWSDayComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // congregation.PtwsDay = PTWSDayComboBox.SelectedDayOfWeek;
        }

        void TMSSMDayComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // congregation.TmssmDay = TMSSMDayComboBox.SelectedDayOfWeek;
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {

        }

        private void BSTMSSM_Checked(object sender, RoutedEventArgs e)
        {
            congregation.BstmssmDay = ((DayOfWeekRadioButton)sender).Day;
        }

        private void PTWS_Checked(object sender, RoutedEventArgs e)
        {
            congregation.PtwsDay = ((DayOfWeekRadioButton)sender).Day;
        }

    }

    public class AudioEndPointComboBoxItem : ComboBoxItem
    {
        private MMDevice endPoint;
        public MMDevice EndPoint
        {
            get
            {
                return endPoint;
            }
        }

        public AudioEndPointComboBoxItem(MMDevice _endPoint)
            : base()
        {
            endPoint = _endPoint;
            this.Content = endPoint.FriendlyName;
        }
    }

    class DayOfWeekRadioButton : RadioButton
    {
        private DayOfWeek day;
        public DayOfWeek Day
        {
            get
            {
                return day;
            }
            set
            {
                day = value;
            }
        }

        public DayOfWeekRadioButton()
            : base()
        {
            FontSize = 12D;
            Margin = new Thickness(0, 0, 0, 6);
        }
    }

    class SongBookRadioButton : RadioButton
    {
        private int id;
        private string title;
        public string Title
        {
            get
            {
                return title;
            }
        }
        public int Id
        {
            get
            {
                return id;
            }
        }

        public SongBookRadioButton(int _id, string _title)
            : base()
        {
            id = _id;
            title = _title;

            Content = title;

            FontSize = 12D;
            Margin = new Thickness(0, 0, 0, 6);
        }
    }
}
